package com.example.harmonyos_orm.net;

import com.zhushenwudi.hmutils.net.BaseNetworkApi;
import com.zhushenwudi.hmutils.net.RequestBaseObserver;
import com.zhushenwudi.hmutils.utils.Log;
import ohos.net.NetManager;
import okhttp3.*;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class Network extends BaseNetworkApi {
    private static Network mInstance;
    private static volatile ApiService mApiService;
    private static final String REQUEST_TYPE = "application/json;charset=UTF-8";
    private static final String TAG = "net";
    private static final int TIMEOUT_5 = 5;
    private static final int TIMEOUT_10 = 10;

    @Override
    public OkHttpClient.Builder setHttpClientBuilder(OkHttpClient.Builder builder) {
        builder.addInterceptor(chain -> {
            // 联网前检查网络情况
            if (!NetManager.getInstance(null).hasDefaultNet()) {
                throw new RequestBaseObserver.NoNetworkException();
            }
            Response response;
            Request request = chain.request()
                    .newBuilder()
                    .build();
            Request.Builder requestBuilder = request.newBuilder();
            Request newRequest = requestBuilder.build();
            response = chain.proceed(newRequest);
            return response;
        }).addNetworkInterceptor(new HttpLoggingInterceptor(message ->
                Log.i(TAG, message)).setLevel(HttpLoggingInterceptor.Level.BODY))
                .connectTimeout(TIMEOUT_10, TimeUnit.SECONDS)
                .readTimeout(TIMEOUT_5, TimeUnit.SECONDS)
                .writeTimeout(TIMEOUT_5, TimeUnit.SECONDS)
                // 忽略HTTPS证书
                .hostnameVerifier(((hostname, session) -> true))
                .protocols(Collections.singletonList(Protocol.HTTP_1_1))
                .build();
        return builder;
    }

    @Override
    public Retrofit.Builder setRetrofitBuilder(Retrofit.Builder builder) {
        return builder.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create());
    }

    public static void init() {
        if (mInstance == null) {
            synchronized (Network.class) {
                mInstance = new Network();
            }
        }
    }

    public static RequestBody createBody(Object obj) {
        MediaType type = MediaType.Companion.parse(REQUEST_TYPE);
        return RequestBody.Companion.create(obj.toString(), type);
    }

    public static ApiService api() {
        if (mApiService == null) {
            synchronized (ApiService.class) {
                mApiService = mInstance.getApi(ApiService.class, ApiService.SERVER_URL);
            }
        }
        return mApiService;
    }
}
